package fun.qu_an.minecraft.fabric.fzbbl.handle;

import fun.qu_an.minecraft.fabric.fzbbl.FZBBL;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.scoreboard.ScoreboardObjective;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

public class PistonBrokeBedrockHandle {
	public static boolean handle(World world, BlockPos bedrockPos, BlockState blockState) {
		if (blockState.getBlock() != Blocks.BEDROCK) return true;
		FZBBL.LOGGER.debug("MachineBedrockBroke: {}, {}", world, bedrockPos);
		if (!FZBBL.MBB.isEmpty()) {
			for (ScoreboardObjective objective : FZBBL.MBB) {
				// 给记分板加分，加分的玩家id等于基岩所在世界($overworld、$the_end、$the_nether)
				world.getScoreboard().getPlayerScore("$" + world.getRegistryKey().getValue(), objective).incrementScore();
				world.getScoreboard().getPlayerScore("$total", objective).incrementScore();
			}
		}
		handleLoosely(world, bedrockPos);
		return true;
	}

	public static boolean handle(World world, BlockPos bedrockPos, BlockState blockState, PlayerEntity player) {
		if (blockState.getBlock() != Blocks.BEDROCK) return true;
		FZBBL.LOGGER.debug("BedrockBroke: {}, {}", bedrockPos, player);
		if (!FZBBL.BBL.isEmpty()) {
			String playerName = player.getEntityName();
			for (ScoreboardObjective objective : FZBBL.BBL) {
				// 给玩家加分
				world.getScoreboard().getPlayerScore(playerName, objective).incrementScore();
			}
		}
		handleLoosely(world, bedrockPos);
		return true;
	}

	private static void handleLoosely(World world, BlockPos bedrockPos) {
		PlayerEntity closestPlayer = getClosestPlayerIn10m(world, bedrockPos); // 最大范围 10.5
		if (closestPlayer == null) return;
		FZBBL.LOGGER.debug("LooselyBedrockBroke: {}, {}", bedrockPos, closestPlayer);
		if (!FZBBL.LBL.isEmpty()) {
			String playerName = closestPlayer.getEntityName();
			// 给10m内最近的玩家加分
			for (ScoreboardObjective objective : FZBBL.LBL) {
				world.getScoreboard().getPlayerScore(playerName, objective).incrementScore();
			}
		}
	}

	@Nullable
	private static PlayerEntity getClosestPlayerIn10m(@NotNull World world, @NotNull BlockPos pos) {
		List<? extends PlayerEntity> players = world.getPlayers();
		if (players.isEmpty()) return null;

		double x = pos.getX() + 0.5F;
		double y = pos.getY() + 0.5F;
		double z = pos.getZ() + 0.5F;

		PlayerEntity closestPlayer = null;
		double d = 10.5; // 最大范围 10.5
		for (PlayerEntity player : players) {
			double d2 = getDistance(player, x, y, z);
			if (d2 < d) {
				d = d2;
				closestPlayer = player;
			}
		}

		// 最大范围 10.5 范围内不存在则返回null
		return closestPlayer;
	}

	private static double getDistance(PlayerEntity player, double x, double y, double z) {
		return Math.sqrt(player.squaredDistanceTo(x, y, z));
	}
}
